<template>
  <div class="common-config-excel-wrap" @click="pageClick">
    <!--  工具条  -->
    <div class="common-table__toolbox">
      <div class="common-toolbox-item" @click.stop="toolboxClick">
        <icon-button
          name="icon-merge"
          content="合并单元格"
          :status="isMergeStatus"
          :disabled="isMergeDisabled"
          @change="handleCellMergeChange"
        ></icon-button>
      </div>
    </div>
    <div class="common-table-wrap">
      <!--   表头   -->
      <!--      <div class="common-table__header">
              <div class="common-header__item" v-for="(column,index) in columns"
                   :style="{width: `${column.w + 3}px`}"
              >
                {{ defaultHeaderList[index] }}
              </div>
            </div>-->
      <!--   列索引   -->
      <!--      <div class="common-table__index">
              <div class="common-index__item" v-for="(row,index) in rows"
                   :style="{height: `${row.h + 3}px`,lineHeight: `${row.h + 3}px`}"
              >
                {{ index + 1 }}
              </div>
            </div>-->
      <!--   表格   -->
      <div class="common-table__container" @click.stop="tableClick">
        <table
          class="common-table__table"
          cellspacing="0"
          :style="tableStyle"
          @click.stop="tableClick"
        >
          <tr class="common-table__tr" v-for="(row, r_index) in table">
            <template v-for="(column, c_index) in row">
              <td
                class="common-table__td"
                :key="column.key"
                v-if="
                  column.data.isMerge === false ||
                  (column.data.isMerge === true &&
                    column.data.mergeType === 'MERGE_MAIN')
                "
                :colspan="column.data.mergeColumn"
                :rowspan="column.data.mergeRow"
                :style="{
                  width: `${columns[c_index].w}px`,
                  height: `${rows[r_index].h}px`,
                }"
                @dblclick="cellDbClick(column, r_index, c_index)"
                @click.stop="cellClick(column, r_index, c_index)"
                @contextmenu="onContextMenu"
              >
                <div
                  class="common-table__cell"
                  data-type="cell"
                  :data-row="r_index"
                  :data-column="c_index"
                  @mousedown.stop="
                    onMousedown($event, column, r_index, c_index)
                  "
                  @mouseup.stop="onMouseup($event, column, r_index, c_index)"
                  :style="{
                    borderColor: column.status.isSelect
                      ? defaultTheme.selectColor
                      : '',
                  }"
                >
                  <div
                    class="common-table__content"
                    data-type="content"
                    :data-row="r_index"
                    :data-column="c_index"
                  >
                    <span
                      >{{
                        column.data.associationType === "M_DATASET" &&
                        column.data.dataset.structure === "S_SINGLE"
                          ? column.data.dataset.value
                          : column.data.associationType === "M_DATASET" &&
                            column.data.dataset.structure === "S_LIST"
                          ? column.data.dataset.name
                          : column.data.content
                      }}
                    </span>
                  </div>
                </div>
              </td>
            </template>
          </tr>
        </table>
      </div>
    </div>
    <common-edit-dialog
      :visible.sync="isEditCell"
      @cancel="isEditCell = false"
      @submit="cellConfirm"
      title="单元格配置"
    >
      <el-form label-width="90px">
        <el-form-item label="展示内容">
          <el-radio-group v-model="currentCellInfo.associationType">
            <el-radio label="M_CONTENT">仅文字</el-radio>
            <el-radio label="M_DATASET">数据集</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="文字内容"
          v-if="currentCellInfo.associationType === 'M_CONTENT'"
        >
          <common-input
            type="textarea"
            v-model="currentCellInfo.content"
          ></common-input>
        </el-form-item>
        <el-form-item
          label="数据集"
          v-if="currentCellInfo.associationType === 'M_DATASET'"
        >
          <choose-dialog
            :class-type="classType"
            :select-id="currentCellInfo.dataset.id"
            :select-name="currentCellInfo.dataset.name"
            @submitDialog="datasetChange"
            @clearInfo="datasetClear"
          >
          </choose-dialog>
        </el-form-item>
        <el-form-item
          label="数据结构"
          v-if="currentCellInfo.associationType === 'M_DATASET'"
        >
          <el-radio-group
            v-model="currentCellInfo.dataset.structure"
            @change="currentCellInfoStructure"
          >
            <el-radio label="S_SINGLE">单条</el-radio>
            <el-radio label="S_LIST" v-if="!currentCellInfo.isMerge"
              >列表</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <div
          v-if="
            currentCellInfo.associationType === 'M_DATASET' &&
            currentCellInfo.dataset.structure === 'S_LIST'
          "
        >
          <el-form-item label="sheet页配置">
            <el-radio-group v-model="currentCellInfo.dataset.isSheetAlone">
              <el-radio :label="0">当前sheet页</el-radio>
              <el-radio :label="1">单独sheet页</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="展示字段">
            <el-select
              v-model="currentCellInfo.dataset.fieldList"
              placeholder="请选择"
              filterable
              multiple
              clearable
              @change="datasetFieldChange"
            >
              <el-option
                v-for="item in datasetFiledList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="字段值"
            v-if="
              currentCellInfo.associationType === 'M_DATASET' &&
              currentCellInfo.dataset.structure === 'S_LIST'
            "
          >
            <!-- <span style="margin-left: 4px; color: #303133">{{
              currentCellInfo.dataset.valueList
            }}</span> -->
            <common-table :data="currentCellInfo.dataset.valueList">
              <el-table-column
                v-for="item in valueList"
                :label="item.lable"
                :prop="item.prop"
                :key="item.prop"
                show-overflow-tooltip
              />
            </common-table>
          </el-form-item>
        </div>

        <el-form-item
          label="展示字段"
          v-if="
            currentCellInfo.associationType === 'M_DATASET' &&
            currentCellInfo.dataset.structure === 'S_SINGLE'
          "
        >
          <el-select
            v-model="currentCellInfo.dataset.field"
            placeholder="请选择"
            filterable
            clearable
            @change="datasetFieldChange"
          >
            <el-option
              v-for="item in datasetFiledList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="字段值"
          v-if="
            currentCellInfo.associationType === 'M_DATASET' &&
            currentCellInfo.dataset.structure === 'S_SINGLE'
          "
        >
          <span style="margin-left: 4px; color: #303133">{{
            currentCellInfo.dataset.value
          }}</span>
        </el-form-item>
      </el-form>
    </common-edit-dialog>
  </div>
</template>

<script>
import { _deepClone } from "@/utils";
import IconButton from "@/views/screenConfig/dataReport/components/IconButton";
import ChooseDialog from "@/views/screenConfig/dataSet/components/chooseDialog";
import { getPreviewReportsData } from "@/api/screenConfig/dataSet";

const CellData = {
  content: "", // 单元格内容
  associationType: "M_CONTENT", // 关联类型 M_CONTENT 仅内容 M_DATASET 关联数据集
  dataset: {
    id: "",
    name: "",
    structure: "S_SINGLE", // 数据结构 S_SINGLE 单条 S_LIST 列表
    field: "", // 单条展示的字段
    fieldList: [], //列表展示字段
    value: "", // 临时展示使用
    valueList: [], //列表临时展示字段
    isSheetAlone: 0, //是否单独sheet页
  }, // 关联的数据集
  isMerge: false, // 是否合并
  mergeType: "MERGE_MAIN", // MERGE_MAIN 主节点 MERGE_PASSIVE 被合并的节点(不渲染)
  mergeRelation: "", // 占用的单元格KEY
  rowIndex: 0, // 当前行 索引
  columnIndex: 0, // 当前列 索引
  mergeRowIndex: 0, // 结束行索引
  mergeColumnIndex: 0, // 结束列索引
  mergeRow: 1, // 合并行数
  mergeColumn: 1, // 合并列数
};

const form = {
  name: "", // 报表名称
  description: "", // 描述
  configuration: {
    rows: [], // 表 行相关配置 (行高)
    columns: [], // 表 列相关配置 (列宽)
    table: [
      {
        // 目前参照上面CellData
      }, // 单元格配置项
    ], // 表格相关配置 存放配置数据的单元格
    // ... 后续可能会拓展其他配置
  }, // 配置项 JSON
};

export default {
  name: "CommonConfigExcel",
  components: {
    IconButton,
    ChooseDialog,
  },
  props: {
    width: {
      type: String,
      default: "200px",
    },
    height: {
      type: String,
      default: "500px",
    },
    configuration: {
      type: Object,
      default: () => ({
        rows: [],
        columns: [],
        table: [],
      }),
    },
    classType: {
      type: [Number, String],
      default: 0,
    },
  },
  data() {
    return {
      valueList: [],

      defaultHeaderList: "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),
      defaultTheme: {
        selectColor: "#4b8cff",
      },
      defaultTableInfo: {
        row: {
          h: 48,
          max_length: 100,
        }, // 表格行 默认配置项
        column: {
          w: 120,
          max_length: 26,
        }, // 表格列 默认配置项
        cell: {
          key: "",
          data: {
            ...CellData,
          }, // 数据
          style: {}, // 单个样式
          status: {
            isEdit: false, // 编辑状态
            isSelect: false, // 选中状态
          }, // 状态
        }, // 表格单元格 默认配置
      }, // 表格 基础配置项信息

      moveEventInfo: {
        row_start: 0, // 起始行
        row_end: 0, // 结束行
        column_start: 0, // 起始列
        column_end: 0, // 结束列
        select: [], // 当前为选中态的单元格索引 [[i,j],[]...]
      }, // 移动过程中起始位置记录

      tableInfo: {
        rowLength: 8, // 表格行数
        columnLength: 8, // 表格列数
        currentRowIndex: 0, // 当前选中的字段行索引
        currentColumnIndex: 0, // 当前选中的字段列索引
      }, // 当前表格信息

      table: [], // 表格 数据 二维表格形式
      columns: [], // 表格列 数据
      rows: [], // 表格行 数据

      isEditCell: false, // 字段配置弹框
      currentCellInfo: {
        ...CellData,
      }, // 当前选中的单元数据
      datasetFiledList: [], // 数据集下面 字段列表
      dataCacheList: [
        {
          id: "",
          dataField: [],
          dataList: [],
          total: 0,
        },
      ],
    };
  },
  computed: {
    tableStyle() {
      let width = this.columns.reduce((r, c) => {
        r = r + c.w + 3;
        return r;
      }, 0);
      let height = this.rows.reduce((r, c) => {
        r = r + c.h + 3;
        return r;
      }, 0);
      return {
        width: `${width}px`,
        height: `${height}px`,
      };
    },
    tableData() {
      return this.configuration?.table ?? [];
    },
    isMergeDisabled() {
      // 默认禁用
      let status = true;
      // 选中多个单元格不禁用 需要优化: 有多个主节点时
      if (this.moveEventInfo.select.length > 1) status = false;
      // 选中一个单元为合并时不禁用
      if (this.currentCellInfo.isMerge) status = false;
      return status;
    },
    isMergeStatus() {
      // 默认 没有合并
      let status = false;

      // 当前选中为合并状态时,可以取消合并
      if (this.currentCellInfo.isMerge) status = true;

      // 选中多个节点时,可以合并.(选中多个优先原则,覆盖上面单个状态)
      if (this.moveEventInfo.select.length > 1) status = false;

      return status;
    },
  },
  methods: {
    //数据接口切换类型置空
    currentCellInfoStructure() {
      this.currentCellInfo.dataset.field = "";
      this.currentCellInfo.dataset.value = "";
      this.currentCellInfo.dataset.fieldList = [];
      this.valueList = [];
      this.currentCellInfo.dataset.valueList = [];
      this.currentCellInfo.dataset.isSheetAlone = 0;
    },
    /**
     * 生成新单元格数据
     * @returns
     */
    getNewCell() {
      let cell = _deepClone(this.defaultTableInfo.cell);
      cell.key = Symbol("单元格KEY");
      return cell;
    },
    handleData() {
      this.setTableSize();
      this.initTable();
    },
    /**
     * 初始化表格行数和列数
     */
    setTableSize() {
      let max_row = this.tableInfo.rowLength,
        max_column = this.tableInfo.columnLength;
      this.tableData.forEach(({ rowIndex, columnIndex }) => {
        if (rowIndex + 1 > max_row) max_row = rowIndex + 1;
        if (columnIndex + 1 > max_column) max_column = columnIndex + 1;
      });

      console.log(`初始化表格: ${max_row}行${max_column}列`);

      this.tableInfo.rowLength = Math.min(max_row + 1, 100);
      this.tableInfo.columnLength = Math.min(max_column + 1, 26);
    },

    /**
     * 初始化表格基础数据
     */
    initTable() {
      let { columnLength, rowLength } = this.tableInfo;
      const row = rowLength,
        column = columnLength;
      let table = [],
        columns = [],
        rows = [];
      for (let i = 0; i < row; i++) {
        let row = [];
        for (let j = 0; j < column; j++) {
          row.push(this.getNewCell());

          if (i === 0) {
            columns.push({
              ...this.defaultTableInfo.column,
            });
          }
        }

        rows.push({
          ...this.defaultTableInfo.row,
        });
        table.push(row);
      }

      this.tableData.forEach((cell) => {
        let { columnIndex, rowIndex } = cell;
        Object.assign(table[rowIndex][columnIndex].data, cell);

        let { id, structure, field, fieldList } = cell.dataset;
        if (
          cell.associationType === "M_DATASET" &&
          structure === "S_SINGLE" &&
          id
        ) {
          this.getDataSetData(id)
            .then((data) => {
              let { dataList } = data;
              if (dataList && dataList instanceof Array && dataList.length) {
                const dataset = table[rowIndex][columnIndex].data.dataset;
                table[rowIndex][columnIndex].data.dataset = {
                  ...dataset,
                  value: dataList[0][field],
                };
              } else {
                console.log(`ID为 [ ${id} ] 的数据集无数据`);
              }
            })
            .catch((err) => {
              console.log("err: ", err);
            });
        }
      });

      this.table = table;
      this.columns = columns;
      this.rows = rows;
    },
    /**
     * 单元格双击事件
     * 双击编辑内容
     * @param column 单元格数据
     * @param row_index 行号
     * @param column_index 列号
     */
    cellDbClick(column, row_index, column_index) {
      Object.keys(this.currentCellInfo).forEach((key) => {
        if (key === "dataset") {
          this.currentCellInfo[key] = _deepClone(column.data[key]);
        } else {
          this.currentCellInfo[key] = column.data[key];
        }
      });
      this.tableInfo.currentRowIndex = row_index;
      this.tableInfo.currentColumnIndex = column_index;
      this.isEditCell = true;

      if (this.currentCellInfo.dataset.id)
        this.getDataSetField(this.currentCellInfo.dataset.id);
    },
    /**
     * 单元格单击事件
     * 单击更新当前选中单元格信息
     * @param column 单元格数据
     * @param row_index 行号
     * @param column_index 列号
     */
    cellClick(column, row_index, column_index) {
      Object.keys(this.currentCellInfo).forEach((key) => {
        if (key === "dataset") {
          this.currentCellInfo[key] = _deepClone(column.data[key]);
        } else {
          this.currentCellInfo[key] = column.data[key];
        }
      });

      this.tableInfo.currentRowIndex = row_index;
      this.tableInfo.currentColumnIndex = column_index;

      this.moveEventInfo.row_start = row_index;
      this.moveEventInfo.column_start = column_index;
      this.moveEventInfo.row_end = row_index;
      this.moveEventInfo.column_end = column_index;

      this.handleCellStatus();
    },
    onContextMenu(e) {
      e.preventDefault();
      return false;
    },
    /**
     * 单元格弹框 确认事件
     */
    cellConfirm() {
      Object.keys(this.currentCellInfo).forEach(
        (key) =>
          (this.table[this.tableInfo.currentRowIndex][
            this.tableInfo.currentColumnIndex
          ].data[key] = this.currentCellInfo[key])
      );

      this.isEditCell = false;
      this.datasetFiledList = [];
      this.autoPopulateTable();
    },
    /**
     * 自动扩充表格行列
     */
    autoPopulateTable() {
      let hasColumnData = false,
        hasRowData = false;

      // 检测最后一行是否有数据
      let lastRow = this.table[this.table.length - 1];
      lastRow.forEach((cell) => {
        if (cell.data.content.length) hasRowData = true;
      });

      // 检测最后一列是否有数据
      let lastColumn = this.table.reduce((r, c) => {
        r.push(c[c.length - 1]);
        return r;
      }, []);
      lastColumn.forEach((cell) => {
        if (cell.data.content.length) hasColumnData = true;
      });

      // 需要增加行
      if (hasRowData) this.addRow();

      // 需要增加列
      if (hasColumnData) this.addColumn();
    },
    /**
     * 添加行
     * @returns {null}
     */
    addRow() {
      if (this.tableInfo.rowLength >= 100) {
        return null;
      }
      let row = [];
      for (let i = 0; i < this.tableInfo.columnLength; i++) {
        row.push(this.getNewCell());
      }
      this.rows.push({
        ...this.defaultTableInfo.row,
      });
      this.table.push(row);
      this.tableInfo.rowLength++;
    },
    /**
     * 添加列
     * @returns {null}
     */
    addColumn() {
      if (this.tableInfo.columnLength >= 26) {
        return null;
      }
      this.columns.push({
        ...this.defaultTableInfo.column,
      });

      for (let i = 0; i < this.tableInfo.rowLength; i++) {
        this.table[i].push(this.getNewCell());
      }
      this.tableInfo.columnLength++;
    },
    deleteRow(index) {},
    deleteColumn(index) {},

    /**
     * 获取鼠标框选的单元格索引范围
     * @returns {{min_row: number, min_column: number, max_row: number, max_column: number}}
     */
    getCellInterval() {
      const { row_start, row_end, column_start, column_end } =
        this.moveEventInfo;

      return {
        min_row: Math.min(row_start, row_end),
        max_row: Math.max(row_start, row_end),
        min_column: Math.min(column_start, column_end),
        max_column: Math.max(column_start, column_end),
      };
    },
    /**
     * 处理单元格状态
     * 内部状态,用于标记单元格是否需要被选中
     */
    handleCellStatus() {
      const { min_row, max_row, min_column, max_column } =
        this.getCellInterval();

      const checkColumnRange = (columnIndex) =>
        columnIndex >= min_column && columnIndex <= max_column;
      const checkRowRange = (rowIndex) =>
        rowIndex >= min_row && rowIndex <= max_row;

      let currentSelect = [];

      this.table.forEach((row, row_index) => {
        row.forEach((column, column_index) => {
          if (checkColumnRange(column_index) && checkRowRange(row_index)) {
            column.status.isSelect = true;

            currentSelect.push([row_index, column_index]);
          } else {
            column.status.isSelect = false;
          }
        });
      });
      this.moveEventInfo.select = currentSelect;
    },
    /**
     * 清除相关事件
     */
    clearEvent() {
      document.onmousemove = undefined;
      document.onmouseup = undefined;
    },
    /**
     * 鼠标按下事件
     * @param event 事件对象
     * @param column 单元格
     * @param row_index 行号
     * @param column_index 列号
     */
    onMousedown(event, column, row_index, column_index) {
      console.log(`在 第${row_index}行,${column_index}列 按下`);
      column.status.isSelect = true;

      this.moveEventInfo.row_start = row_index;
      this.moveEventInfo.column_start = column_index;
      this.moveEventInfo.row_end = row_index;
      this.moveEventInfo.column_end = column_index;

      this.handleCellStatus();

      document.onmousemove = (e) => {
        let { type, row, column } = e.target.dataset;
        row = parseInt(row);
        column = parseInt(column);

        if (type) {
          if (
            this.moveEventInfo.row_end === row &&
            this.moveEventInfo.column_end === column
          ) {
          } else {
            if (this.moveEventInfo.row_end !== row) {
              this.moveEventInfo.row_end = row;
            }
            if (this.moveEventInfo.column_end !== column) {
              this.moveEventInfo.column_end = column;
            }
            this.handleCellStatus();
          }
        }
      };

      // 全局鼠标松开方法
      document.onmouseup = () => {
        this.clearEvent();
      };
    },
    /**
     * 鼠标松开事件
     * @param event 事件对象
     * @param column 单元格
     * @param row_index 行号
     * @param column_index 列号
     */
    onMouseup(event, column, row_index, column_index) {
      console.log(`在 第${row_index}行,${column_index}列 松开`);
      this.clearEvent();
      column.status.isSelect = true;
    },
    /**
     * 处理单元格合并信息
     * @param status
     */
    handleCellMergeChange(status) {
      if (status) {
        this.handleCellMerge();
      } else {
        this.handleCellCancelMerge();
      }
    },
    /**
     * 合并单元格
     */
    handleCellMerge() {
      this.currentCellInfoStructure();
      let { min_row, max_row, min_column, max_column } = this.getCellInterval();

      // MERGE_MAIN 主节点 MERGE_PASSIVE 被合并的节点(不渲染)

      let merge = [];
      for (let i = min_row; i <= max_row; i++) {
        for (let j = min_column; j <= max_column; j++) {
          merge.push([i, j]);
        }
      }

      let mainCell = this.table[min_row][min_column];

      // 当起点单元格数据为数据集列表类型时，不允许合并
      if (mainCell.data.dataset.structure === "S_LIST") {
        this.$message({
          type: "warning",
          message: "起点单元格不允许是数据集列表类型!",
        });
      } else {
        merge.forEach(([i, j]) => {
          this.clearMerge(this.table[i][j]);
        });

        let passiveCellList = merge.slice(1);

        passiveCellList.forEach(([i, j]) => {
          let passiveCell = this.table[i][j];
          passiveCell.data.isMerge = true; // 是否合并
          passiveCell.data.mergeType = "MERGE_PASSIVE"; // MERGE_MAIN 主节点 MERGE_PASSIVE 被合并的节点(不渲染)
          passiveCell.data.mergeRelation = `${min_row}_${min_column}`; // 占用的单元格KEY
          passiveCell.data.mergeRowIndex = 0; // 结束行索引
          passiveCell.data.mergeColumnIndex = 0; // 结束列索引
          passiveCell.data.mergeRow = 1; // 合并行数
          passiveCell.data.mergeColumn = 1; // 合并列数
          passiveCell.status.isSelect = false;
        });

        let mergeRelation = passiveCellList
          .reduce((r, c) => {
            r.push(c.join("_"));
            return r;
          }, [])
          .join(",");

        mainCell.data.isMerge = true; // 是否合并
        mainCell.data.mergeType = "MERGE_MAIN"; // MERGE_MAIN 主节点 MERGE_PASSIVE 被合并的节点(不渲染)
        mainCell.data.mergeRelation = mergeRelation; // 占用的单元格KEY
        mainCell.data.mergeRowIndex = max_row; // 结束行索引
        mainCell.data.mergeColumnIndex = max_column; // 结束列索引
        mainCell.data.mergeRow = max_row - min_row + 1; // 合并行数
        mainCell.data.mergeColumn = max_column - min_column + 1; // 合并列数
        mainCell.status.isSelect = true;

        this.cellClick(mainCell, min_row, min_column);
      }
    },
    /**
     * 取消合并
     */
    handleCellCancelMerge() {
      this.currentCellInfoStructure();
      let { min_row, max_row, min_column, max_column } = this.getCellInterval();
      let cell = this.table[min_row][min_column];
      this.clearMerge(cell);
      this.cellClick(cell, min_row, min_column);
    },
    /**
     * 重置单元格关联信息
     * @param cell 单元格
     */
    clearMerge(cell) {
      if (cell.data.isMerge) {
        let mergeType = cell.data.mergeType;
        let mergeRelation = cell.data.mergeRelation;

        cell.data.isMerge = false;
        cell.data.mergeType = "MERGE_MAIN"; // MERGE_MAIN 主节点 MERGE_PASSIVE 被合并的节点(不渲染)
        cell.data.mergeRelation = ``; // 占用的单元格KEY
        cell.data.mergeRowIndex = 0; // 结束行索引
        cell.data.mergeColumnIndex = 0; // 结束列索引
        cell.data.mergeRow = 1; // 合并行数
        cell.data.mergeColumn = 1; // 合并列数
        cell.status.isSelect = false;

        if (mergeType === "MERGE_MAIN" && mergeRelation.length) {
          mergeRelation.split(",").forEach((p) => {
            let [i, j] = p.split("_");
            this.clearMerge(this.table[i][j]);
          });
        }

        if (mergeType === "MERGE_PASSIVE" && mergeRelation.length) {
          let [i, j] = mergeRelation.split("_");
          this.clearMerge(this.table[i][j]);
        }

        cell.dataset = CellData.dataset;
      }
    },
    checkCellEdit(cell) {
      return (
        cell.content.length ||
        cell.associationType === "M_DATASET" ||
        cell.isMerge
      );
    },
    /**
     * 获取表格相关配置项
     * @returns {{column: (*), row: (*), table: (*)}}
     */
    getTableData() {
      // 只保存有数据的单元格
      const list = this.table.reduce((row_result, row_current, r_index) => {
        let row_current_temp = _deepClone(row_current);

        let hasContent = row_current_temp.reduce(
          (column_result, column_current, c_index) => {
            column_current.data.dataset = {
              id: column_current.data.dataset.id,
              name: column_current.data.dataset.name,
              structure: column_current.data.dataset.structure,
              field: column_current.data.dataset.field,
              fieldList: column_current.data.dataset.fieldList,
              isSheetAlone: column_current.data.dataset.isSheetAlone,
            };
            let cell = column_current.data;

            if (this.checkCellEdit(cell)) {
              column_result.push({
                ...cell,
                rowIndex: r_index, // 当前行 索引
                columnIndex: c_index, // 当前列 索引
              });
            }
            return column_result;
          },
          []
        );
        row_result.push(...hasContent);

        return row_result;
      }, []);

      return {
        rows: [],
        columns: [],
        table: list,
      };
    },
    clearAllCellStatus() {
      this.table.forEach((row) => {
        row.forEach((column) => {
          column.status.isSelect = false;
          column.status.isEdit = false;
        });
      });
    },
    /**
     * 页面点击事件
     */
    pageClick() {
      console.log("pageClick");
      this.clearAllCellStatus();
      this.resetCurrentCellInfo();
      this.moveEventInfo.select = [];
    },
    resetCurrentCellInfo() {
      Object.keys(this.currentCellInfo).forEach((key) => {
        this.currentCellInfo[key] = CellData[key];
      });
    },
    tableClick(e) {
      console.log("tableClick");
      // e.stopPropagation()
    },
    toolboxClick(e) {},
    datasetChange(row) {
      const { id, name } = row;

      this.currentCellInfo.dataset.id = id;
      this.currentCellInfo.dataset.name = name;
      this.datasetFieldClear();
      if (id) this.getDataSetField(id);
    },
    datasetClear() {
      this.currentCellInfo.dataset.id = "";
      this.currentCellInfo.dataset.name = "";
      this.datasetFieldClear();
    },
    datasetFieldClear() {
      this.datasetFiledList = [];
      this.currentCellInfo.dataset.field = "";
      this.currentCellInfo.dataset.value = "";
      this.currentCellInfo.dataset.fieldList = [];
      this.currentCellInfo.dataset.valueList = [];
      this.valueList = [];
    },
    setCache(data) {
      let index = this.dataCacheList.findIndex((ds) => ds.id === data.id);
      if (index === -1) {
        this.dataCacheList.push(data);
      } else {
        this.dataCacheList.splice(index, 1, data);
      }
    },
    getDataSetByCache(id) {
      return this.dataCacheList.find((ds) => ds.id === id);
    },
    getDataSetData(id) {
      return new Promise((resolve, reject) => {
        let ds = this.getDataSetByCache(id);
        if (ds) {
          console.log(`ID为 [ ${id} ] 从缓存中获取数据`);
          resolve(ds);
        } else {
          console.log(`ID为 [ ${id} ] 从接口中获取数据`);
          getPreviewReportsData({ datasetId: id })
            .then((res) => {
              if (res.code === 200) {
                let { dataField, dataList, total } = res.data;

                this.setCache({
                  id,
                  dataField,
                  dataList,
                  total,
                });

                resolve(res.data);
              } else {
                reject();
              }
            })
            .catch((err) => {
              reject();
            });
        }
      });
    },

    getDataSetField(id) {
      this.getDataSetData(id)
        .then((data) => {
          let { dataField } = data;
          this.datasetFiledList = dataField.reduce((r, c) => {
            r.push({
              label: c.fieldDescribe,
              value: c.fieldName,
            });
            return r;
          }, []);
        })
        .catch(() => {
          this.datasetFiledList = [];
        });
    },
    datasetFieldChange() {
      // 数据结构 S_SINGLE 单条 S_LIST 列表
      let { id, structure, field, fieldList } = this.currentCellInfo.dataset;
      if (structure === "S_SINGLE") {
        this.getDataSetData(id)
          .then((data) => {
            let { dataList } = data;
            if (dataList && dataList instanceof Array && dataList.length) {
              this.currentCellInfo.dataset.value = dataList[0][field];
            }
          })
          .catch((err) => {
            console.error("获取数据集数据异常: ", err);
          });
      }
      if (structure === "S_LIST") {
        this.getDataSetData(id)
          .then((data) => {
            let { dataList } = data;
            if (dataList && dataList instanceof Array && dataList.length) {
              this.valueList = [];
              this.currentCellInfo.dataset.valueList = dataList.slice(0, 10);
              fieldList.map((item) => {
                this.valueList.push({
                  lable: item,
                  prop: item.toString(),
                });
              });
            }
          })
          .catch((err) => {
            console.error("获取数据集数据异常: ", err);
          });
      }
    },
  },
  mounted() {
    this.handleData();
  },
};
</script>

<style scoped lang="scss">
.common-config-excel-wrap {
  width: 100%;
  height: 100%;
  padding-top: 20px;
  box-sizing: border-box;

  .common-table__toolbox {
    height: 32px;
    display: flex;
    align-items: center;
    padding-left: 20px;

    .common-toolbox-item {
    }
  }

  .common-table-wrap {
    position: relative;
    width: 100%;
    height: calc(100% - 32px);

    .common-table__header {
      position: absolute;
      height: 20px;
      width: calc(100% - 20px);
      left: 20px;
      top: 0;
      display: flex;
      align-items: center;
      overflow-x: scroll;
      overflow-y: hidden;

      &::-webkit-scrollbar {
        height: 0 !important;
        width: 0 !important;
      }

      .common-header__item {
        border-width: 0.5px;
        border-style: solid;
        border-color: rgba(255, 255, 255, 0);
        text-align: center;
        flex: 0 0 auto;
        background-color: #f9fafb;
      }
    }

    .common-table__index {
      position: absolute;
      width: 20px;
      height: calc(100% - 20px);
      top: 20px;
      left: 0;
      overflow-x: hidden;
      overflow-y: scroll;

      &::-webkit-scrollbar {
        height: 0 !important;
        width: 0 !important;
      }

      .common-index__item {
        border-width: 0.5px;
        border-style: solid;
        border-color: rgba(255, 255, 255, 0);
        text-align: center;
        flex: 0 0 auto;
        background-color: #f9fafb;
      }
    }

    .common-table__container {
      position: absolute;
      left: 20px;
      top: 20px;
      overflow: scroll;
      width: calc(100% - 20px);
      height: calc(100% - 20px);

      .common-table__table {
        width: 100%;
        height: 100%;
        border: 0.5px solid #eee;

        .common-table__tr {
          .common-table__td {
            border: 0.5px solid #eee;
            cursor: pointer;

            .common-table__cell {
              width: 100%;
              height: 100%;
              border-width: 0.5px;
              border-style: solid;
              border-color: rgba(255, 255, 255, 0);
              display: flex;
              justify-content: flex-start;
              align-items: center;
              white-space: break-spaces;
              font-size: 14px;

              .common-table__content {
                user-select: none;
              }
            }
          }
        }
      }
    }
  }
}
</style>
